package com.ycz.zheng_springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ycz.zheng_springboot.entity.common.Constants;
import com.ycz.zheng_springboot.dto.UserDTO;
import com.ycz.zheng_springboot.dto.UserPasswordDTO;
import com.ycz.zheng_springboot.entity.Menu;
import com.ycz.zheng_springboot.entity.User;
import com.ycz.zheng_springboot.exception.ServiceException;
import com.ycz.zheng_springboot.mapper.RoleMapper;
import com.ycz.zheng_springboot.mapper.RoleMenuMapper;
import com.ycz.zheng_springboot.mapper.UserMapper;
import com.ycz.zheng_springboot.service.IMenuService;
import com.ycz.zheng_springboot.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ycz.zheng_springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 岳彩郑
 * @since 2022-04-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private static final Log LOG = Log.get();

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDTO login(UserDTO userDTO) {

        User user = getUserInfo(userDTO);
        // 处理异常情况
        if (user == null) {
            throw new ServiceException(Constants.CODE_401, "用户名或密码错误呀");
        } else {
            BeanUtil.copyProperties(user, userDTO, true);// 拷贝属性
            //设置token
            String token = TokenUtils.getToken(user.getId().toString(), user.getPassword());
            userDTO.setToken(token);
            String role = user.getRole();// 获取用户角色 查询的是字段flag  ROLE_ADMIN,ROLE_USER
            // 设置角色菜单
            List<Menu> roleMenu = getRoleMenu(role);
            userDTO.setMenus(roleMenu);

            return userDTO;
        }

    }

    @Override
    public User register(UserDTO userDTO) {
        User user = getUserInfo(userDTO);
        if (user == null) {
            user = new User();
            BeanUtil.copyProperties(userDTO, user, true);// 拷贝属性
            user.setCreateTime(new Date());
            user.setNickname("user_" + RandomUtil.randomString(5));
            save(user);// 保存用户信息
        } else {
            throw new ServiceException(Constants.CODE_600, "用户名已存在");
        }
        return null;
    }

    /**
     * 修改密码
     * @param userPasswordDTO
     */
    @Override
    public void updatePassword(UserPasswordDTO userPasswordDTO) {
        int update = userMapper.updatePassword(userPasswordDTO);
        if (update < 1) {
            throw new ServiceException(Constants.CODE_600, "密码错误");
        }
    }


    private User getUserInfo(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());
        User one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误，请联系管理员");
        }
        return one;
    }

    /**
     * 获取用户菜单
     *
     * @param roleFlag
     * @return
     */
    private List<Menu> getRoleMenu(String roleFlag) {
        Integer roleId = roleMapper.selectByFlag(roleFlag);
        // 当前角色的所有菜单id集合
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);

        // 查出系统所有的菜单(树形)
        List<Menu> menus = menuService.findMenu("");
        // new一个最后筛选完成之后的list
        List<Menu> roleMenus = new ArrayList<>();
        // 筛选当前用户角色的菜单
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getId())) {
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();
            // removeIf()  移除 children 里面不在 menuIds集合中的 元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        return roleMenus;
    }
}
